<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">分类管理</text>
      <view class="action-buttons">
        <text class="add-btn" @click="navigateTo('add')">+ 新增分类</text>
      </view>
    </view>

    <!-- 分类列表 -->
    <uni-list>
      <uni-swipe-action ref="swipeAction">
        <uni-swipe-action-item v-for="(category, index) in categories" :key="index" :right-options="swipeOptions" @click="handleSwipeClick($event, category)">
          <uni-list-item :title="category.name" :note="`排序: ${category.sort}`" showArrow @click="editCategory(category)" :clickable="true">
            <template v-slot:footer>
              <view class="sort-handle" @click.stop="">
                <uni-icons type="bars" size="20" color="#999"></uni-icons>
              </view>
            </template>
          </uni-list-item>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </uni-list>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import {getGoodsCategories, deleteGoodsCategory} from '@/api/goodsCategory.js';
import {getMerchantId} from '@/utils/merchant.js';


// 获取 uni-swipe-action 实例
const swipeAction = ref(null);
const categories = ref([]);
const swipeOptions = [
  {
    text: '删除',
    style: {
      backgroundColor: '#dd524d'
    }
  }
];

onShow(() => {
  // 加载分类数据
  loadCategories();
})

const loadCategories = async () => {
  const {data} = await getGoodsCategories(getMerchantId());
  categories.value = data;
}

const navigateTo = (type) => {
  uni.navigateTo({
    url: `/pages/goods/category-edit?type=${type}&merchantId=${getMerchantId()}`
  });
};

const editCategory = (category) => {
  uni.navigateTo({
    url: `/pages/goods/category-edit?type=edit&id=${category.id}`
  });
};

const handleSwipeClick = (e, category) => {
  if (e.index === 0) {
    uni.showModal({
      title: '提示',
      content: '确定删除该分类吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await deleteGoodsCategory(category.id);
            loadCategories();
            uni.showToast({ title: '删除成功', icon: 'success' });
          } catch (error) {
            uni.showToast({ title: '删除失败', icon: 'error' });
          }
        }
        console.log('用户点击取消', swipeAction.value);
        swipeAction.value?.closeAll();
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.add-btn {
  font-size: 28rpx;
  color: #FF7F50;
}

.sort-handle {
  padding: 10rpx 20rpx;
}
</style>